<template>
  <el-card>
    <!-- 查询区域 -->
    <el-form :model="queryParams" inline label-width="80px" class="search-form">
      <el-form-item label="医生姓名">
        <el-select v-model="queryParams.doctorName" clearable placeholder="请选择医生" style="width: 150px">
          <el-option label="全部" value=""/>
          <el-option v-for="v in doctorNameOpts" :key="v" :label="v" :value="v"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="success" @click="handleAdd">新增排班</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table :data="tableData" border stripe style="width: 100%; margin:12px 0">
      <el-table-column prop="id" label="ID" width="60" fixed/>
      <el-table-column prop="doctorName" label="员工姓名" width="120"/>
      <el-table-column prop="startTime" label="时段开始时间" width="160">
        <template #default="{row}">
          {{ formatDateTime(row.startTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="endTime" label="时段结束时间" width="160">
        <template #default="{row}">
          {{ formatDateTime(row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="maxNum" label="最大可挂号数" width="120" align="center"/>
      <el-table-column label="状态" width="100" align="center">
        <template #default="{row}">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'" effect="light">
            {{ row.status === 1 ? '可挂号' : '不可用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{row}">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDel(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        :page-size="pagination.pageSize"
        :current-page="pagination.pageNum"
        :page-sizes="[5, 10, 20, 50]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination-container"
    />
  </el-card>

  <!-- 新增/编辑弹窗 -->
  <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px" :close-on-click-modal="false">
    <el-form :model="form" ref="formRef" label-width="100px" :rules="formRules">
      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item label="医生" prop="doctorId">
            <el-select v-model="form.doctorId" clearable placeholder="请选择医生" style="width: 100%">
              <el-option v-for="doc in doctorOptions" :key="doc.id" :label="doc.name" :value="doc.id"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最大号源" prop="maxNum">
            <el-input-number v-model="form.maxNum" :min="1" :max="100" :controls="false" style="width: 100%"/>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
                v-model="form.startTime"
                type="datetime"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择开始时间"
                style="width: 100%"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
                v-model="form.endTime"
                type="datetime"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择结束时间"
                style="width: 100%"/>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select v-model="form.status" style="width: 100%">
              <el-option :value="1" label="可挂号"/>
              <el-option :value="0" label="不可用"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible=false">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import {ElMessage, ElMessageBox} from 'element-plus'
import {findAllTimeSlot, findTimeSlotByDoctor, addTimeSlot, updateTimeSlot, deleteTimeSlot} from '../api/timeSlot.js'
import {selectAll} from '../api/staff.js'

export default {
  name: 'TimeSlotView',
  data() {
    return {
      // 查询参数
      queryParams: {
        doctorName: ''
      },
      // 分页参数
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      // 表格数据
      tableData: [],
      // 弹窗控制
      dialogVisible: false,
      dialogTitle: '',
      isAdd: true,
      // 表单数据
      form: {},
      // 表单验证规则
      formRules: {
        doctorId: [{ required: true, message: '请选择医生', trigger: 'change' }],
        startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
        endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
        maxNum: [{ required: true, message: '请输入最大号源数', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }]
      },
      // 下拉选项
      doctorNameOpts: [],
      doctorOptions: []
    }
  },
  mounted() {
    this.loadData()
    this.loadDoctorOptions()
  },
  methods: {
    // 加载表格数据
    async loadData() {
      try {
        if (this.queryParams.doctorName) {
          // 如果有医生姓名条件，先找到对应的医生ID
          const doctor = this.doctorOptions.find(doc => doc.name === this.queryParams.doctorName)
          if (doctor) {
            // 使用按医生查询的API
            const {data: res} = await findTimeSlotByDoctor(doctor.id)
            if (res.code === 200) {
              this.tableData = res.obj || []
              this.pagination.total = this.tableData.length
            } else {
              ElMessage.error(res.msg || '获取数据失败')
            }
          } else {
            this.tableData = []
            this.pagination.total = 0
          }
        } else {
          // 没有查询条件时使用 findAllTimeSlot
          const params = {
            pageNum: this.pagination.pageNum,
            pageSize: this.pagination.pageSize
          }
          const {data: res} = await findAllTimeSlot(params)
          if (res.code === 200) {
            this.tableData = res.obj.list || []
            this.pagination.total = res.obj.total
          } else {
            ElMessage.error(res.msg || '获取数据失败')
          }
        }
      } catch (e) {
        ElMessage.error('加载数据失败')
        console.error(e)
      }
    },

    // 加载医生下拉选项
    async loadDoctorOptions() {
      try {
        const {data: res} = await selectAll()
        if (res.code === 200) {
          this.doctorOptions = res.obj || []
          this.doctorNameOpts = [...new Set(this.doctorOptions.map(doc => doc.name).filter(Boolean))].sort()
        }
      } catch (e) {
        console.error(e)
      }
    },

    // 查询
    handleQuery() {
      this.pagination.pageNum = 1
      this.loadData()
    },

    // 重置
    handleReset() {
      this.queryParams = {doctorName: ''}
      this.pagination.pageNum = 1
      this.loadData()
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.loadData()
    },

    // 当前页变化
    handleCurrentChange(val) {
      this.pagination.pageNum = val
      this.loadData()
    },

    // 格式化日期时间显示
    formatDateTime(dateTime) {
      if (!dateTime) return ''
      // 如果是 Date 对象
      if (dateTime instanceof Date) {
        return dateTime.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false
        }).replace(/\//g, '-')
      }
      // 如果是字符串
      const date = new Date(dateTime)
      if (isNaN(date.getTime())) {
        return String(dateTime) // 如果无法解析，返回原字符串
      }
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      }).replace(/\//g, '-')
    },

    // 新增
    handleAdd() {
      this.isAdd = true
      this.dialogTitle = '新增排班'
      this.form = {
        doctorId: '',
        startTime: '',
        endTime: '',
        maxNum: 10,
        status: 1
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.formRef) {
          this.$refs.formRef.clearValidate()
        }
      })
    },

    // 编辑
    handleEdit(row) {
      this.isAdd = false
      this.dialogTitle = '编辑排班'
      this.form = {
        id: row.id,
        doctorId: row.doctorId,
        startTime: row.startTime,
        endTime: row.endTime,
        maxNum: row.maxNum,
        status: row.status
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.formRef) {
          this.$refs.formRef.clearValidate()
        }
      })
    },

    // 删除
    handleDel(row) {
      ElMessageBox.confirm('确认删除该排班记录？', '提示', {type: 'warning'})
          .then(async () => {
            const {data: res} = await deleteTimeSlot(row.id)
            if (res.code === 200) {
              ElMessage.success('删除成功')
              this.loadData()
            } else {
              ElMessage.error(res.msg || '删除失败')
            }
          })
          .catch(() => {})
    },

    // 提交表单
    async submitForm() {
      try {
        await this.$refs.formRef.validate()

        // 校验开始时间必须早于结束时间
        const startTime = new Date(this.form.startTime)
        const endTime = new Date(this.form.endTime)
        if (startTime >= endTime) {
          ElMessage.error('开始时间必须早于结束时间')
          return
        }
        const now = new Date()
        if (startTime < now) {
          ElMessage.error('开始时间不能早于当前时间')
          return
        }

        const api = this.isAdd ? addTimeSlot : updateTimeSlot
        const {data: res} = await api(this.form)
        if (res.code === 200) {
          ElMessage.success(this.isAdd ? '新增成功' : '修改成功')
          this.dialogVisible = false
          this.loadData()
        } else {
          ElMessage.error(res.obj || '操作失败')
        }
      } catch (e) {
        console.error(e)
        ElMessage.error('提交失败，请检查数据')
      }
    }
  }
}
</script>

<style scoped>
.search-form {
  margin-bottom: 12px;
}

.pagination-container {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  font-size: 14px;
}
</style>